import 'package:film/model/film_model.dart';
import 'package:film/model/film_play_model.dart';
import 'package:film/service/api_service.dart';
import 'package:get/get.dart';

class FilmController extends GetxController {
  final DioService dioService = DioService();
  // 影片列表
  var recommendFilmList = <Film>[].obs;
  // 页面数据，使用.obs使其成为响应式变量
  final filmData = FilmPlayModel.getDummyData().obs;

  // 当前选中的剧集索引
  final selectedEpisodeIndex = 0.obs;

  // 视频是否正在加载
  final isLoading = true.obs;
  var film = Film().obs;
  var url = '';
  var vodId;

  var videoItemList = <VideoItem>[].obs;

  @override
  void onInit() {
    super.onInit();
    vodId = Get.arguments['vodId'];
    _initializeVideo();
  }

  /// 获取视频
  Future<void> _initializeVideo() async {
    try {
      final ApiResponse<VideoDetails> response = await dioService.getVideoByID(vodId: vodId);
      if (response.success && response.data != null) {
        film.value = Film.fromJson(response.data!.video);
        videoItemList.value = parseVideoItems(film.value.vodPlayUrl ?? "");
        getRecommendFilmList(film.value.vodYear!);
        dioService.addVideoRecord(videoId: vodId, look: '1');
      }
    } catch (e) {
      print('获取视频失败: $e');
    }
  }

  List<VideoItem> parseVideoItems(String vodPlayUrl) {
    final List<VideoItem> result = [];
    final episodes = vodPlayUrl.split('#');
    for (var episode in episodes) {
      final parts = episode.split('\$');
      if (parts.length == 2) {
        result.add(VideoItem(
          name: parts[0].trim(),
          code: parts[1].trim(),
        ));
      }
    }
    return result;
  }

  @override
  void onClose() {
    // 释放资源
    print('正在释放资源...');
    super.onClose();
  }

  /// 选择剧集
  Future<void> selectEpisode(int index) async {
    try {
      // selectedEpisodeIndex.value = index;
      // 暂停当前视频
      // await betterPlayerController.pause();

      // 在实际应用中，这里会切换视频源
      // 这里模拟切换视频源
      // await _initializeVideoPlayer();

      print('切换到: ${filmData.value.episodes[index]}');
    } catch (e) {
      print('切换剧集失败: $e');
    }
  }

  /// 获取推荐视频
  Future<void> getRecommendFilmList(String vodYear) async {
    try {
      SearchCriteria criteria = SearchCriteria(page: "1", limit: "12", resultType: "1", vodYear: vodYear);
      ApiResponse<List<Film>> response = await dioService.searchVideo(criteria);
      if (response.success) {
        recommendFilmList.assignAll(response.data ?? []);
      }
    } catch (e) {
      print('获取推荐视频失败: $e');
    }
  }

  /// 添加视频记录(观看记录|追番记录)
  Future<void> addVideoRecord(
    String videoId,
    String follow,
  ) async {
    final ApiResponse<void> response = await dioService.addVideoRecord(
      videoId: videoId,
      follow: follow,
    );
    if (response.success) {
      Get.snackbar(
        '成功',
        '追番成功！',
        duration: Duration(seconds: 1),
      );
    }
  }
}
